import re
import random
from django.shortcuts import render
from django.views import View
from django.http import HttpResponse
from django.utils.decorators import method_decorator
from django.core.mail import send_mail
from django_redis import get_redis_connection

from utils.verifyUtil import verifyParam
from utils.resFormatUtil import ResFormat
from ffmall.settings import EMAIL_HOST_USER
from celery_tasks.email.tasks import send_email_task

# Create your views here.
class EmailVerificationView(View):
    DURATION = 3  # 有效时长，单位分钟
    EMAIL_KEY = 'email:verification:%s'

    @method_decorator(verifyParam('email'))
    def post(self, request):
        # 实现邮箱格式的验证
        email = request.POST.get('email')

        # 验证邮箱的格式
        re_email = r'(\w+)@(\w+)\.(\w+)'
        if not re.match(re_email, email):
            return ResFormat(status='PARAM_ERROR').json_response()
        verification_code = random.randint(100000, 999999)  # 6位随机验证码
        # 发送邮件
        # self.send_email_task(email, verification_code, self.DURATION)
        send_email_task.delay(email, verification_code, self.DURATION)

        # 'email:verification:%s' % email
        # return HttpResponse('test')
        return ResFormat().json_response()


